<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
</head>
<body>
<script type="text/javascript">
    let socket;
    if(window.WebSocket){
        socket = new WebSocket('ws://localhost:8899/ws');
        //收到服务端发送的消息
        socket.onmessage = function (event) {
            console.log(event);
            let ta = document.getElementById('response-text');
            ta.value = ta.value + '\n' + event.data;
        };

        //连接成功
        socket.onopen = function (event) {
            console.log(event);
            let ta = document.getElementById('response-text');
            ta.value = "连接开启";
        };
        
        //连接断开
        socket.onclose = function (event) {
            console.log(event);
            let ta = document.getElementById('response-text');
            ta.value = ta.value + '\n' + '连接关闭';
        };

        //异常发生
        socket.onerror = function (event) {
            console.log(event);
            let ta = document.getElementById('response-text');
            ta.value = ta.value + '\n' + '发生异常';
        }
    }
    else {
        alert('浏览器不支持WebSocket');
    }

    function send() {
        let message = document.getElementById('message-ta').value;
        if(!window.WebSocket){
            return;
        }

        if(socket.readyState === WebSocket.OPEN){
            socket.send(message);
        }
        else{
            alert('连接尚未开启');
        }
    }

</script>
<form onsubmit="return false;">
    <textarea name="message" id="message-ta" style="width: 400px; height: 200px;"></textarea>
    <input type="button" value="发送消息" onclick="send();">
    <h3>服务端输出:</h3>
    <textarea id="response-text" style="width: 400px; height: 300px;"></textarea>
    <input type="button" onclick="javascript: document.getElementById('response-text').value = ''" value="清空输出">
</form>
</body>
</html>